package com.byxy.dao.impl;

import com.byxy.dao.AdminRuleDao;
import com.byxy.model.AdminGroup;
import com.byxy.model.AdminRule;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AdminRuleDaoImpl implements AdminRuleDao {
    @Autowired
    private SessionFactory sessionFactory;

    @Override
    public void save(AdminRule adminRule) {
        if (adminRule.getParent().getId() == null) {
            adminRule.setParent(null);
        }
        sessionFactory.getCurrentSession().save(adminRule);
    }

    @Override
    public void delete(Integer id) {
        AdminRule adminRule = (AdminRule) sessionFactory.getCurrentSession().load(AdminRule.class, id);
        // 使用多对多时, 被控方要这样才能删除
        for (AdminGroup e : adminRule.getAdminGroups()) {
            e.getAdminRules().remove(adminRule);
        }
        sessionFactory.getCurrentSession().delete(adminRule);
    }

    @Override
    public void update(AdminRule adminRule) {
        if (adminRule.getParent().getId() == null) {
            adminRule.setParent(null);
        }
        sessionFactory.getCurrentSession().update(adminRule);
    }

    @Override
    public AdminRule get(Integer id) {
//        AdminRule adminRule = (AdminRule) sessionFactory.getCurrentSession().load(AdminRule.class, id);
//        System.out.println(adminRule);
        return (AdminRule) sessionFactory.getCurrentSession().load(AdminRule.class, id);
    }

    @Override
    public List<AdminRule> listPage(Integer pageNum, Integer pageSize, String search) {
        //language=HQL
        String hql = "FROM AdminRule WHERE title LIKE :search";
        Query query = sessionFactory.getCurrentSession().createQuery(hql);
        query.setParameter("search", "%".concat(search).concat("%"));
        if (pageNum > 0 && pageSize > 0) {
            query.setFirstResult((pageNum - 1) * pageSize);
            query.setMaxResults(pageSize);
        }
        return query.list();
    }

    @Override
    public Integer count(String search) {
        //language=HQL
        String hql = "SELECT COUNT(*) FROM AdminRule WHERE title LIKE :search";
        return ((Long) sessionFactory.getCurrentSession().createQuery(hql)
                .setParameter("search", "%".concat(search).concat("%"))
                .uniqueResult())
                .intValue();
    }

    /*
        只有level为1或者2才会是父级菜单
     */
    @Override
    public List<AdminRule> listPid() {
        //language=HQL
        String hql = "FROM AdminRule WHERE level IN (1, 2)";
        return sessionFactory.getCurrentSession().createQuery(hql).list();
    }
}
